package com.sto.stoapp.db;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.sto.stoapp.StoConfig;
import com.sto.stoapp.entity.DataBusinessEntity;
import com.sto.stoapp.entity.UploadPictureInforEntity;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.manager.AccessControlManager;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.util.DateUtil;
import com.sto.stoapp.util.StringUtil;
import com.sto.stoapp.util.UnifiedStaticType;

/**
 * 业务数据manager
 * 
 * @author Administrator
 * 
 */
public class StoDataBaseOperation extends StoDataBase {

	// 未发送的状态
	private final String unsent = "未";
	private static StoDataBaseOperation stoDataBaseOperation = null;
	private Context context;

	public StoDataBaseOperation(Context context) {
		super(context);
		this.context = context;
	}

	public static StoDataBaseOperation getInstance(Context context) {
		if (stoDataBaseOperation == null) {
			stoDataBaseOperation = new StoDataBaseOperation(context);
		}
		return stoDataBaseOperation;
	}

	/**
	 * 插入扫描数据
	 * 
	 * @param entity
	 * @param item
	 * @return
	 */
	@SuppressLint("SimpleDateFormat")
	public boolean insert(DataBusinessEntity entity, EnumTableNames item) {
		long res = -1;

		String tableName = item.getTableName();

		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			if (!StoConfig.isCanRepetition) {
				if (isAlreadyScaned(tableName, entity)) {

					return false;
				}
			}

			SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
			try {

				res = db.insert(tableName, null,
						buildContentValues(buildEntity(entity)));

			} finally {

				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}

			if (res > 0) {
				return true;
			} else {
				return false;
			}
		}
	}


	public boolean isAlreadyScaned(String tableName, DataBusinessEntity entity) {
		int res = 0;
		StoTableFieldName tableFieldName = new StoTableFieldName();
		SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);

		Cursor cursor = db.rawQuery(
				"select count(*) from " + tableName + " where "
						+ tableFieldName.BAR_CODE_NUMBER + " = ? and "
						+ tableFieldName.SCAN_DATE2 + " = ? and "
						+ tableFieldName.EXPRESS_TYPE + " = ? and "
						+ tableFieldName.METADATA + " = ? ",
				new String[] { entity.getBar_code_number(),
						DateUtil.getTodayDate("-"), entity.getExpress_type(),
						"1" });

		if (cursor != null && cursor.moveToFirst()) {
			res = cursor.getInt(0);
		}
		closeCursor(cursor);
		closeDb(UnifiedStaticType.WRITE_DATABASE);
		return res > 0;
	}

	public boolean replace(DataBusinessEntity entity, EnumTableNames item) {
		if (entity.getWeight() == null || "".equals(entity.getWeight()))
			return false;
		DataBusinessEntity data = buildEntity(entity);
		SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
		StoTableFieldName tableFieldName = new StoTableFieldName();
		int row = 0;
		boolean result = false;
		try {
			String sql = tableFieldName.BAR_CODE_NUMBER + "=?" + " and "
					+ tableFieldName.WEIGHT + " !='' and "
					+ tableFieldName.SEND_STATE + "='未' and "
					+ tableFieldName.METADATA + " ='1'";
			row = db.delete(item.getTableName(), sql,
					new String[] { entity.getBar_code_number() });
			if (row > 0) {
				result = insert(data, item);
			}

		} catch (Exception e) {

			e.printStackTrace();
		} finally {

			closeDb(UnifiedStaticType.WRITE_DATABASE);
		}

		return result;
	}

	@SuppressLint("SimpleDateFormat")
	private DataBusinessEntity buildEntity(DataBusinessEntity entity) {
		SimpleDateFormat sDateFormat = new SimpleDateFormat(
				UnifiedStaticType.DATE_TIME_FORMAT);
		String date = sDateFormat.format(new java.util.Date());
		String arrays[] = date.split(" ");
		entity.setScan_date(arrays[1]);
		entity.setScan_time(arrays[0]);
		entity.setDateAndTime(DateUtil.getDateTime());
		// // 机器唯一码
		entity.setUnique_code(StoFilePreference.getInstance(context)
				.getMachineCode());
		entity.setPdaUuid(StringUtil.getUUID());
		return entity;
	}

	private ContentValues buildContentValues(DataBusinessEntity entity) {
		StoTableFieldName tableFieldName = new StoTableFieldName();
		// db.beginTransaction();
		ContentValues contentValues = new ContentValues();
		// PDA_UUID
		contentValues.put(tableFieldName.PDA_UUID, StringUtil.getUUID());
		// 是否删除表
		contentValues.put(tableFieldName.AUXOPCODE, entity.getAuxOpCode());
		// 单号类型
		contentValues.put(tableFieldName.EXPTYPE, entity.getCodeType());

		contentValues.put(tableFieldName.SCAN_DATE_AND_TIME,
				entity.getDateAndTime());
		// 业务类型
		contentValues
				.put(tableFieldName.COMMAND_TYPE, entity.getCommand_type());
		// 程序角色
		contentValues.put(tableFieldName.ROLE, AccessControlManager
				.getInstance(context).getRole());
		// 上下站编号、目的地 /收件员、派件员编号
		contentValues
				.put(tableFieldName.NEXT_STATION, entity.getNext_station());
		// 袋号
		contentValues.put(tableFieldName.BAG_NUMBER, entity.getBag_number());
		// 包号
		contentValues.put(tableFieldName.PACK_NUMBER, entity.getPack_number());
		// 扫描日期 月日年
		contentValues.put(tableFieldName.SCAN_DATE, entity.getScan_date());
		// 扫描时间 年月日
		contentValues
				.put(tableFieldName.SCAN_DATE2, DateUtil.getTodayDate("-"));
		// 扫描时间
		contentValues.put(tableFieldName.SCAN_TIME, entity.getScan_time());
		// 物品类型/功能类别
		contentValues.put(tableFieldName.FUNCTION_TYPE,
				entity.getFunction_type());
		// 快件类型
		contentValues
				.put(tableFieldName.EXPRESS_TYPE, entity.getExpress_type());
		// 运单编码/包条码/车签条码
		contentValues.put(tableFieldName.BAR_CODE_NUMBER,
				entity.getBar_code_number());
		// 扫描员编号
		contentValues.put(tableFieldName.SCANNER_NUMBER,
				entity.getScanner_number());
		// 班次
		contentValues.put(tableFieldName.SHIFT, entity.getShift());
		// 异常签收原因编号/路由号
		contentValues.put(tableFieldName.REASON_NUMBER,
				entity.getReason_number());
		// 代收款、车牌号
		contentValues.put(tableFieldName.CAR_NUMBER, entity.getCar_number());
		// 货单标识/车牌ID条码
		contentValues
				.put(tableFieldName.CARID_NUMBER, entity.getCarID_number());
		// 备注/收件人手机号/签收人/同行名称
		contentValues.put(tableFieldName.REMARK_NAME, entity.getRemark_name());
		// 重量
		contentValues.put(tableFieldName.WEIGHT, entity.getWeight());
		// 输入重量
		contentValues.put(tableFieldName.INPUT_WEIGHT, entity.getWeight());
		// 寄件人手机号
		contentValues.put(tableFieldName.SEND_PHONE, entity.getSend_phone());
		// 巴枪唯一码
		contentValues.put(tableFieldName.UNIQUE_CODE, entity.getUnique_code());
		// 件数
		contentValues.put(tableFieldName.NUMBER, entity.getNumber());
		// 运费
		contentValues.put(tableFieldName.SHIPPING, entity.getShipping());
		// 到付款
		contentValues.put(tableFieldName.TO_PAYMENT, entity.getTo_payment());
		// 支付方式
		contentValues.put(tableFieldName.PAYMENT, entity.getPayment());
		// 收件人
		contentValues.put(tableFieldName.RECV_PERSON, entity.getRecv_person());
		// 寄件人
		contentValues.put(tableFieldName.SEND_PERSON, entity.getSend_person());
		// 用户定义3
		contentValues.put(tableFieldName.USER_DEFINED3,
				entity.getUser_defined3());
		// 用户定义4
		contentValues.put(tableFieldName.USER_DEFINED4,
				entity.getUser_defined4());
		// 用户定义5
		contentValues.put(tableFieldName.USER_DEFINED5,
				entity.getUser_defined5());
		// 上传时间
		contentValues.put(tableFieldName.UPLOAD_TIME, entity.getUpload_time());
		// 网点编号
		contentValues.put(tableFieldName.NET_CODE, entity.getNet_code());
		// 工号
		contentValues.put(tableFieldName.JOB_NUMBER, entity.getJob_number());
		// 发送状态
		contentValues.put(tableFieldName.SEND_STATE, unsent);
		// 不同的标志(15)
		contentValues.put(tableFieldName.DIFFERENT_FLAG,
				entity.getDifferent_flag());
		// 元数据标识
		contentValues.put(tableFieldName.METADATA, entity.getMetadata());

		// db.execSQL("BEGIN EXCLUSIVE");

		return contentValues;

	}

	/**
	 * 删除扫描数据
	 * 
	 * @param TABLE_STATUS
	 * @param code
	 * @return
	 */
	// public boolean deleteScanData(EnumTableNames table_status, String code) {
	// synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
	// StoTableFieldName tableFieldName = new StoTableFieldName();
	//
	// int ret = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE)
	// .delete(table_status.getTableName(),
	// tableFieldName.BAR_CODE_NUMBER + "=? and "
	// + tableFieldName.SEND_STATE + "=? and "
	// + tableFieldName.SCAN_DATE2
	// + "=(select Max(scan_date2) from  "
	// + table_status.getTableName() + " where "
	// + tableFieldName.BAR_CODE_NUMBER
	// + " = ?)  ",
	// new String[] { code, UnifiedStaticType.NO_STATUS,
	// code });
	// closeDb(UnifiedStaticType.WRITE_DATABASE);
	// return ret > 0;
	// }
	// }

	/**
	 * 删除扫描数据
	 * 
	 * @param TABLE_STATUS
	 * @param code
	 * @return
	 */
	/*
	 * public int deleteScanDataCount(int table_status, String code) {
	 * synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) { int ret = 0;
	 * StoTableFieldName tableFieldName = new StoTableFieldName(); String
	 * tablename = EnumTableNames.values()[table_status] .getTableName(); ret =
	 * getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE).delete( tablename,
	 * tableFieldName.BAR_CODE_NUMBER + " = ? and " + tableFieldName.SEND_STATE
	 * + " = ?", new String[] { code, UnifiedStaticType.NO_STATUS });
	 * closeDb(UnifiedStaticType.WRITE_DATABASE); return ret; } }
	 */


	public int deleteScanData(int table_status, String code) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			int ret = 0;
			StoTableFieldName tableFieldName = new StoTableFieldName();
			String tablename = EnumTableNames.values()[table_status]
					.getTableName();

			// SQLiteDatabase db =
			// getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);

			// 增加删除记录
			SimpleDateFormat sDateFormat = new SimpleDateFormat(
					"HH:mm:ss yyyy-MM-dd");
			String date = sDateFormat.format(new java.util.Date());
			String arrays[] = date.split(" ");

			// String pdaUUid = StringUtil.getUUID();
			// String sqlSelectInsert = "insert into "
			// + tablename
			// + "(command_type, pdauuid, auxopcode, role, exptype, "
			// + "metadata, next_station, bag_number, pack_number, "
			// + "scan_date, scan_time, function_type, express_type, "
			// + "bar_code_number, scanner_number, "
			// + "shift, reason_number, car_number, carID_number, remark_name, "
			// + "weight, input_weight, send_phone, "
			// +
			// "unique_code, number, shipping, to_payment, payment, recv_person, "
			// +
			// "send_person, upload_time, net_code, job_number, user_defined3, "
			// +
			// "user_defined4, user_defined5, send_state, different_flag, scan_date2) "
			// + "select command_type, replace (pdauuid,pdauuid,'"
			// + pdaUUid
			// + "') as pdauuid,replace(auxopcode, auxopcode,"
			// + "'DELETED'"
			// + ") as auxopcode, "
			// + "role, exptype, replace(metadata, metadata,"
			// + "''"
			// + ") as metadata ,next_station, "
			// +
			// "bag_number, pack_number, scan_date, replace(scan_time, scan_time, '"
			// + arrays[0]
			// + "') as scan_time, function_type, express_type, "
			// +
			// "bar_code_number, scanner_number, shift, reason_number, car_number, carID_number, "
			// +
			// "remark_name, weight, input_weight, send_phone, unique_code, number, "
			// +
			// "shipping, to_payment, payment, recv_person, send_person, upload_time, net_code, "
			// + "job_number, user_defined3, user_defined4, user_defined5, "
			// + "send_state, different_flag, replace(scan_date2, scan_date2, '"
			// + arrays[1] + "') as scan_date2 from " + tablename
			// + " where " + "bar_code_number='" + code
			// + "' and metadata='1' and send_state='未'";
			//
			// SQLiteStatement statement = null;

			SimpleDateFormat sDateFormat2 = new SimpleDateFormat(
					UnifiedStaticType.DATE_TIME_FORMAT);
			String date2 = sDateFormat2.format(new java.util.Date());
			String arrays2[] = date2.split(" ");
			SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
			try {

				ContentValues values = new ContentValues();
				values.put(tableFieldName.METADATA, "");
				values.put(tableFieldName.AUXOPCODE, "DELETED");
				values.put(tableFieldName.SCAN_DATE, arrays2[1]);
				values.put(tableFieldName.SCAN_TIME, arrays2[0]);
				values.put(tableFieldName.SCAN_DATE2, arrays[1]);
				// if (ret > 0) {
				ret = db.update(
						tablename,
						values,
						tableFieldName.BAR_CODE_NUMBER
								+ "=? and metadata=? and auxOpCode=? and send_state=?",
						new String[] { code, "1", "NEW", "未" });
				// }
				// db.setTransactionSuccessful();

			} catch (Exception ex) {
				ex.printStackTrace();
			} finally {
				// db.endTransaction();
				// if (statement != null) {
				// statement.close();
				// }
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}

			return ret;
		}
	}

	/**
	 * 删除扫描数据
	 * 
	 * @param TABLE_STATUS
	 * @param code
	 * @param type
	 * @return
	 */
	// public boolean deleteScanData(int table_status, String code, String type)
	// {
	// synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
	// StoTableFieldName tableFieldName = new StoTableFieldName();
	// String tablename = EnumTableNames.values()[table_status]
	// .getTableName();
	// int ret = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE)
	// .delete(tablename,
	// tableFieldName.BAR_CODE_NUMBER + " = ? and "
	// + tableFieldName.SEND_STATE + " = ? and "
	// + tableFieldName.DIFFERENT_FLAG + " = ?",
	// new String[] { code, UnifiedStaticType.NO_STATUS,
	// type });
	// closeDb(UnifiedStaticType.WRITE_DATABASE);
	// return ret > 0;
	// }
	// }


	public String getBagNumber(EnumTableNames currentStatus, String code) {
		String bagNumber = null;
		try {
			StoTableFieldName fieldName = new StoTableFieldName();
			String tableName = currentStatus.getTableName();
			String cmd = ("select " + fieldName.BAG_NUMBER + " from "
					+ tableName + " where " + fieldName.BAR_CODE_NUMBER
					+ " =  ? and " + fieldName.SEND_STATE + " = ? ");
			synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
				Cursor c = getCursor(UnifiedStaticType.READ_DATABASE, cmd,
						new String[] { code, UnifiedStaticType.NO_STATUS });
				if (c != null) {
					if (c.moveToFirst()) {
						bagNumber = c.getString(c
								.getColumnIndex(fieldName.BAG_NUMBER));
					}
					closeCursor(c);
				}

				closeDb(UnifiedStaticType.READ_DATABASE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("getBagNumber", e.getMessage());
		}

		return bagNumber;
	}


	public int StatisticsBagNumberCount(EnumTableNames currentStatus,
			String code) {
		int count = 0;
		try {

			StoTableFieldName fieldName = new StoTableFieldName();
			String tableName = currentStatus.getTableName();
			// String bagCmd = ("select count(*) from " + tableName + " where "
			// + fieldName.BAG_NUMBER + " = ? and " + fieldName.SEND_STATE +
			// " = ?");
			String bagCmd = ("select count(*) from " + tableName + " where "
					+ fieldName.BAG_NUMBER + "=(select bag_number from "
					+ tableName + " where " + fieldName.BAR_CODE_NUMBER + "=?)"
					+ " and " + fieldName.SEND_STATE + " = ? and metadata='1'");

			// String bagNumber = getBagNumber(currentStatus, code);
			synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
				Cursor cur = getCursor(UnifiedStaticType.READ_DATABASE, bagCmd,
						new String[] { code, UnifiedStaticType.NO_STATUS });
				if (cur != null) {
					if (cur.moveToFirst()) {
						count = cur.getInt(0);
					}
					closeCursor(cur);
				}

				closeDb(UnifiedStaticType.READ_DATABASE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("StatisticsBagNumberCount", e.getMessage());
		}

		return count;
	}

	public void clearTableData(String sql) {

		try {
			SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
			db.execSQL(sql);
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("clearTableData", e.getMessage());
		} finally {
			closeDb(UnifiedStaticType.WRITE_DATABASE);
		}
	}


	public void updatePicturePath(String table, String filePath, String code,
			String businessType) {
		// System.out.println("path============" + filePath);
		StoTableFieldName tableFieldName = new StoTableFieldName();
		SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
		// 保存图片路径
		String sql = "update " + table + " set " + tableFieldName.USER_DEFINED4
				+ " = ? where " + tableFieldName.BAR_CODE_NUMBER + " = ? and "
				+ tableFieldName.COMMAND_TYPE + " = ?";
		db.execSQL(sql, new String[] { "N" + filePath, code, businessType });
		closeDb(UnifiedStaticType.WRITE_DATABASE);
	}


	public List<UploadPictureInforEntity> getPicturePath(
			EnumTableNames currentStatus) {
		List<UploadPictureInforEntity> strPath = new ArrayList<UploadPictureInforEntity>();
		String tableName = currentStatus.getTableName();
		try {
			StoTableFieldName fieldName = new StoTableFieldName();
			String cmd = "select * from " + tableName + " where "
					+ fieldName.USER_DEFINED4 + " != ? and "
					+ fieldName.USER_DEFINED5 + " != ?";
			synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
				Cursor c = getCursor(UnifiedStaticType.WRITE_DATABASE, cmd,
						new String[] { "", UnifiedStaticType.YES_STATUS });
				if (c != null && c.moveToFirst()) {
					do {
						UploadPictureInforEntity pictureEntity = new UploadPictureInforEntity();

						pictureEntity.setBillCode(c.getString(c
								.getColumnIndex(fieldName.BAR_CODE_NUMBER)));
						pictureEntity.setPath(c.getString(c
								.getColumnIndex(fieldName.USER_DEFINED4)));
						pictureEntity.setEmployee(c.getString(c
								.getColumnIndex(fieldName.JOB_NUMBER)));
						pictureEntity.setSiteName(c.getString(c
								.getColumnIndex(fieldName.SEND_PERSON)));
						if (currentStatus == EnumTableNames.STATUS_TABLE_SALESMAN_SIGN) {
							pictureEntity
									.setScanType(UnifiedStaticType.SIGN_PICTURE_UPLOAD);// 签收
						} else if (currentStatus == EnumTableNames.STATUS_TABLE_PROBLEM) {
							pictureEntity
									.setScanType(UnifiedStaticType.PROBLEM_PICTURE_UPLOAD);// 问题件
						} else {
							pictureEntity
									.setScanType(UnifiedStaticType.AVIATION_PROBLEM_PICTURE_UPLOAD);// 航空问题件
						}
						if (pictureEntity.getPath().equals("")) {
							continue;
						}
						strPath.add(pictureEntity);
					} while (c.moveToNext());

					closeCursor(c);
				}

				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("getPicturePath", e.getMessage());
		}

		return strPath;
	}


	public void updatePicturePath(String type, String code) {
		String tableName = null;
		if (type.equals(UnifiedStaticType.SIGN_PICTURE_UPLOAD)) {
			tableName = EnumTableNames.STATUS_TABLE_SALESMAN_SIGN
					.getTableName();
		} else if (type.equals(UnifiedStaticType.PROBLEM_PICTURE_UPLOAD)) {
			tableName = EnumTableNames.STATUS_TABLE_PROBLEM.getTableName();
		} else {
			tableName = EnumTableNames.STATUS_TABLE_AVIATION_PROBLEM
					.getTableName();
		}

		StoTableFieldName tableFieldName = new StoTableFieldName();
		SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
		// 保存图片路径
		String sql = "update " + tableName + " set "
				+ tableFieldName.USER_DEFINED5 + " = ? where "
				+ tableFieldName.BAR_CODE_NUMBER + " = ? and "
				+ tableFieldName.USER_DEFINED4 + " != ''";
		db.execSQL(sql, new String[] { UnifiedStaticType.YES_STATUS, code });
	}


	public int StatisticsPictureCount(EnumTableNames currentStatus) {
		int count = 0;
		try {
			StoTableFieldName fieldName = new StoTableFieldName();
			String tableName = currentStatus.getTableName();
			String sql = ("select count(*) from " + tableName + " where "
					+ fieldName.USER_DEFINED4 + " != '' and "
					+ fieldName.USER_DEFINED5 + " != ?");
			synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
				Cursor cur = getCursor(UnifiedStaticType.READ_DATABASE, sql,
						new String[] { UnifiedStaticType.YES_STATUS });
				if (cur != null) {
					if (cur.moveToFirst()) {
						count = cur.getInt(0);
					}
					closeCursor(cur);
				}

				closeDb(UnifiedStaticType.READ_DATABASE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("StatisticsPictureCount", e.getMessage());
		}

		return count;
	}


	public boolean deletePicture(int table_status, String code) {
		boolean ret = false;
		String pathPicture = "";

		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			String tableName = EnumTableNames.values()[table_status]
					.getTableName();
			try {
				StoTableFieldName fieldName = new StoTableFieldName();
				String sql = "select * from " + tableName + " where "
						+ fieldName.BAR_CODE_NUMBER + " = ? and "
						+ fieldName.USER_DEFINED4 + " != ''";
				Cursor c = getCursor(UnifiedStaticType.WRITE_DATABASE, sql,
						new String[] { code });
				if (c != null && c.moveToNext()) {
					pathPicture = c.getString(c
							.getColumnIndex(fieldName.USER_DEFINED4));
					closeCursor(c);
				}
				closeDb(UnifiedStaticType.WRITE_DATABASE);

				if (!pathPicture.equals("")) {
					File file = new File(pathPicture.substring(1));
					if (file.exists()) {
						file.delete();
					}
					ret = true;
				}

			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("getPicturePath", e.getMessage());
			}

		}
		return ret;
	}


	public long getCountByStateAndJob(EnumTableNames currentStatus,
			String jobNumber, String state, String start, String end) {
		long count = 0;
		// synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
		Cursor c = null;
		try {
			StoTableFieldName fieldName = new StoTableFieldName();
			String tableName = currentStatus.getTableName();
			String jobNumStr = "";
			if (jobNumber != null) {
				jobNumStr = " and " + fieldName.JOB_NUMBER + "= ? ";
			}
			String stateStr = fieldName.SEND_STATE + "='" + state + "'";
			if (state == null) {
				stateStr = "(" + fieldName.SEND_STATE + "= '未'  or "
						+ fieldName.SEND_STATE + "='已')";
			}
			String sql = "select count(*) from " + tableName
					+ " where 1=1 and " + fieldName.AUXOPCODE + "='NEW' "
					+ " and " + fieldName.METADATA + "='1' and " + stateStr
					+ jobNumStr + "  and " + fieldName.SCAN_DATE_AND_TIME
					+ " >= ?" + " and " + fieldName.SCAN_DATE_AND_TIME + "<=?";
			if (jobNumber == null) {
				c = getCursor(UnifiedStaticType.READ_DATABASE, sql,
						new String[] { start, end });
			} else {
				c = getCursor(UnifiedStaticType.READ_DATABASE, sql,
						new String[] { jobNumber, start, end });
			}

			if (c != null) {
				c.moveToFirst();
				// 获取数据中的LONG类型数据
				count = c.getLong(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("getCountByState", e.toString());

		} finally {

			closeCursor(c);

			closeDb(UnifiedStaticType.READ_DATABASE);
		}
		return count;
		// }
	}


	public List<String> getCodesInfoByJobAndState(EnumTableNames currentStatus,
			String jobNum, String state, String start, String end) {
		// synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
		List<String> codes = new ArrayList<String>();
		Cursor c = null;
		try {
			StoTableFieldName fieldName = new StoTableFieldName();
			String tableName = currentStatus.getTableName();
			String stateCondition = "";
			String jobCondition = "";

			if (state != null) {
				stateCondition = " and " + fieldName.SEND_STATE + "=? ";

			}

			if (jobNum != null) {
				jobCondition = " and " + fieldName.JOB_NUMBER + "=? ";
			}
			String sql = "select " + fieldName.BAR_CODE_NUMBER + ","
					+ fieldName.SEND_STATE + " from " + tableName
					+ " where 1=1 and " + fieldName.METADATA + "='1'  "
					+ jobCondition + stateCondition + " and "
					+ fieldName.SCAN_DATE_AND_TIME + " >= ?" + " and "
					+ fieldName.SCAN_DATE_AND_TIME + "<=?" + " order by "
					+ fieldName.SCAN_DATE_AND_TIME + " desc ";

			if (state == null && jobNum == null) {
				c = getCursor(UnifiedStaticType.READ_DATABASE, sql,
						new String[] { start, end });
			} else if (state == null && jobNum != null) {
				c = getCursor(UnifiedStaticType.READ_DATABASE, sql,
						new String[] { jobNum, start, end });
			} else if (state != null && jobNum == null) {
				c = getCursor(UnifiedStaticType.READ_DATABASE, sql,
						new String[] { state, start, end });
			} else if (state != null && jobNum != null) {
				c = getCursor(UnifiedStaticType.READ_DATABASE, sql,
						new String[] { jobNum, state, start, end });
			}

			if (c != null && c.moveToFirst()) {
				do {
					String code = c.getString(c
							.getColumnIndex(fieldName.BAR_CODE_NUMBER));
					String sqlstate = c.getString(c
							.getColumnIndex(fieldName.SEND_STATE));
					codes.add(code + "         " + sqlstate);
				} while (c.moveToNext());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (c != null) {
				closeCursor(c);
			}
			closeDb(UnifiedStaticType.READ_DATABASE);
		}
		return codes;
		// }
	}
}
